package com.droidcar;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import act.droidcar.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

/**
 * Adaptador para exibcao das imagens do veiculo a partir da WEB.
 */
public class AdapterImagens extends BaseAdapter {

	
	private ArrayList<String> listaImagens;
	private ArrayList<Drawable> listaImagensD;	
	private Context myContext;

	
	public AdapterImagens(Context c, ArrayList<String> pListaImagens) { 
		this.myContext = c; 
		this.listaImagens = pListaImagens;
	}
	
    /**
     * Retorna a quantidade de itens
     */	
	public int getCount() { 
		return this.listaImagens.size(); 
	}
	
	public Object getItem(int position) { 
		return position; 
	}
	
    /**
     * Retorna o item de acordo com a posicao dele na tela.
     */	
	public long getItemId(int position) { 
		return position; 
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		
		ImageView view = new ImageView(this.myContext);
		if(listaImagensD == null)
			listaImagensD = new ArrayList<Drawable>(listaImagens.size());
		if(listaImagensD.size() <= position){
			Drawable d = LoadImageFromWebOperations(listaImagens.get(position));
			listaImagensD.add(d); 
		}
					
		view.setImageDrawable(listaImagensD.get(position));
		return view;
		
	}
	
	public float getScale(boolean focused, int offset) {
		return Math.max(0, 1.0f / (float)Math.pow(2,Math.abs(offset)));	
	}
	
	/**
	 * Metodo para carregamento da imagem em um objeto Drawable
	 */	
	public Drawable LoadImageFromWebOperations(String url)

    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }catch (Exception e) {
            System.out.println("Exc="+e);
            return null;
        }
    }    	
	

}
